<?php
/**
 * Internationalization (i18n) class. Provides language loading and translation
 * methods without dependencies on [gettext](http://php.net/gettext).
 *
 * Typically this class would never be used directly, but used via the __()
 * function, which loads the message and replaces parameters:
 *
 * // Display a translated message
 * echo __('Hello, world');
 *
 * // With parameter replacement
 * echo __('Hello, :user', array(':user' => $username));
 *
 * @package    Kohana
 * @category   Base
 * @author     Kohana Team
 * @copyright  (c) 2008-2011 Kohana Team
 * @license    http://kohanaframework.org/license
 */
class I18n
{

	/**
	 *
	 * @var string target language: en-us, es-es, zh-cn, etc
	 */
	protected static $lang = 'en-us';

	/**
	 *
	 * @var array cache of loaded languages
	 */
	protected static $_cache = array();
	

	/**
	 * Get and set the target language.
	 *
	 * // Get the current language
	 * $lang = I18n::lang();
	 *
	 * // Change the current language to Spanish
	 * I18n::lang('es-es');
	 *
	 * @param
	 *       	 string new language setting
	 * @return string
	 * @since 3.0.2
	 */
	public static function lang ($lang = NULL)
	{
		if ($lang)
		{
			self::$lang = str_replace(array(
				' ', 
				'_'
			), '-', strtolower($lang));
		}
		return self::$lang;
	}

	/**
	 * Returns the translation table for a given language.
	 *
	 * // Get all defined Spanish messages
	 * $messages = I18n::load('es-es');
	 *
	 * @param
	 *       	 string language to load
	 * @return array
	 */
	public static function load ($_pack = 'common' ,$_lang = NULL)
	{
		if (! $_lang) $_lang = self::$lang;
		if (isset(self::$_cache[$_lang][$_pack])) return self::$_cache[$_lang][$_pack];
		$table = array();
		$path = "i18n/{$_lang}/" . str_replace(array(
			'.'
		), DIRECTORY_SEPARATOR, $_pack) . '.php';
		return self::$_cache[$_lang][$_pack] = include ($path);
	}

	/**
	 * Returns translation of a string.
	 * If no translation exists, the original
	 * string will be returned. No parameters are replaced.
	 *
	 * $hello = I18n::get('Hello friends, my name is :name');
	 *
	 * @param
	 *       	 string text to translate
	 * @param
	 *       	 string target language
	 * @return string
	 */
	public static function path ($pack ,$key ,$lang = NULL)
	{
		$arr = self::load($pack, $lang);
		return Arr::path($arr, $key, NULL);
	}

	/**
	 * 调用 语言包中的串
	 *
	 * @param $pack string       	
	 * @param $key string       	
	 * @param $values array       	
	 * @param $default string       	
	 * @param $lang string       	
	 */
	public static function __ ($pack ,$key ,$values = NULL ,$lang = NULL)
	{
		$string = self::path($pack, $key, $lang);
		if(!$string)return $key;
		if (empty($values)) return $string;
		$rs = array();
		if(is_array($values))
		foreach ($values as $k => $v)
		{
			if ($k[0] !== ':')
			{
				$rs[":{$k}"] = $v;
			}
			else
			{
				$rs[$k] = $v;
			}
		}
		return empty($values) ? $string : strtr($string, $rs);
	}
}

